package com.pancm.test.excel;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.handler.WriteHandler;
import com.alibaba.excel.write.metadata.WriteSheet;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 *  excel 导出工具类
 *  支持多线程批量导出
 */

public class ExcelExportUtil {

    private static final int BATCH_SIZE = 1000;  // 每批处理的数据条数
    private static final int THREAD_COUNT = 5;    // 线程数量

    /**
     * 批量导出 Excel
     *
     * @param response HTTP 响应对象
     * @param data     要导出的数据集合
     * @param sheetName 工作表名称
     * @param fileName 导出的文件名
     * @param clazz    数据类类型
     * @throws Exception 导出过程中的异常
     */
    public static <T> void export(HttpServletResponse response, List<T> data,Class<T> clazz,
                                  String sheetName, String fileName, List<List<String>> headLists,
                                  WriteHandler writeHandler1,WriteHandler writeHandler2) throws Exception {
        // 设置响应属性
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        // 创建线程池
        ExecutorService executorService = Executors.newFixedThreadPool(THREAD_COUNT);
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), clazz).build()) {
            WriteSheet writeSheet = EasyExcel.writerSheet(0, sheetName)
                    .head(headLists)
                    .registerWriteHandler(writeHandler1)
                    .registerWriteHandler(writeHandler2)
                    .build();
            int totalRecords = data.size();
            // 提交任务
            for (int i = 0; i < totalRecords; i += BATCH_SIZE) {
                int start = i;
                int end = Math.min(start + BATCH_SIZE, totalRecords);
                List<T> batchData = data.subList(start, end);
                executorService.submit(() -> {
                    synchronized (excelWriter) {
                        excelWriter.write(batchData, writeSheet);
                    }
                });
            }
        } finally {
            executorService.shutdown(); // 关闭线程池  
        }
    }


}